//
//  JMPickerView.m
//  NbTest
//
//  Created by admin on 12-3-10.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "JMPickerView.h"
//#import "NingBoBankAppDelegate.h"
#import "SheetViewController.h"
#import "JMEnv.h"
#import "AppDelegate.h"
#define isIOS7 ( [[[[UIDevice currentDevice] systemVersion] substringToIndex:1] intValue]>=7 )
#define isIOS8 ( [[[[UIDevice currentDevice] systemVersion] substringToIndex:1] intValue]>=8 )

 static JMPickerView* _Instance_JMPickerViews ;

@implementation JMPickerView

@synthesize _arrayPickView,_titleLabel,_actionSheet,_pickView,_tableView,_YYSelString, _selectRow;
@synthesize _YYSelectRow,iDelegate;

+ (id) getInstance{
    //static JMPickerView* _Instance_JMPickerViews ;
    
    if (! _Instance_JMPickerViews)
    {
        _Instance_JMPickerViews = [[JMPickerView alloc]init];
    }
    
    return _Instance_JMPickerViews;
}


+ (void) delocateInstance
{
    //static JMPickerView* _Instance_JMPickerViews ;
    
    if (! _Instance_JMPickerViews)
    {
        [_Instance_JMPickerViews dealloc];
        _Instance_JMPickerViews = nil;
    }
    
}


- (id) init
{
    if (self = [super init])
    {
        if(isIOS8){
             _sheetVC = [[SheetViewController alloc] init];
        }else{
            _actionSheet=[[UIActionSheet alloc] initWithTitle:@"\n\n\n\n\n\n\n\n\n\n\n\n\n"
                                                delegate:nil
                                                cancelButtonTitle:nil
                                                destructiveButtonTitle: nil
                                                otherButtonTitles:nil, nil];
            //确定、取消按钮
            UIBarButtonItem *buttonItemFlexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
            UIBarButtonItem *buttonItemRight = [[UIBarButtonItem alloc] initWithTitle:@"确定"
                                                                         style: UIBarButtonItemStyleBordered
                                                                         target:self
                                                                         action:@selector(selectDateAffirm)];
            
            UIBarButtonItem *buttonItemLeft  = [[UIBarButtonItem alloc] initWithTitle:@"取消"
                                                                         style:UIBarButtonItemStyleBordered
                                                                         target:self
                                                                         action:@selector(selectDateCanceled)];
            
            UIToolbar *tool=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
            tool.barStyle=UIBarStyleDefault;
            if (isIOS7)
            {
                tool.frame = CGRectMake(8, 0, 304, 44) ;
                [tool setBarTintColor:ENV.iToolBarColor];
                tool.barStyle=UIBarStyleBlackOpaque;
                [tool setTintColor:[UIColor whiteColor]];
            }
            
            tool.backgroundColor=[UIColor clearColor];
            NSArray *array = [[NSArray alloc] initWithObjects:buttonItemLeft,buttonItemFlexible,buttonItemRight,nil];
            [tool setItems: array];
            [buttonItemLeft  release];
            [buttonItemFlexible release];
            [buttonItemRight release];
            [array release];
            
            [_actionSheet addSubview:tool];
            [tool release];
            //选择
            _pickView = [[UIPickerView alloc]init];
            _pickView.frame=CGRectMake(0, 44, 320, 216.0);
            _pickView.delegate = self;
            _pickView.dataSource = self;
            _pickView.showsSelectionIndicator = YES;
            
            UILabel* label =  [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
            _titleLabel = label;
            //[label release];//在这里release会报错
            _titleLabel.text = @" title ";
            _titleLabel.textColor = [UIColor whiteColor];
            _titleLabel.font = [UIFont boldSystemFontOfSize:19];
            _titleLabel.textAlignment = UITextAlignmentCenter;
            _titleLabel.backgroundColor = [UIColor clearColor];
            [_actionSheet addSubview:_titleLabel];
            [label release];
            
            [_actionSheet addSubview:_pickView];
        }
    }
    
    return self;
}


+(void)PopViewWithYYString:(NSMutableString*)aString andIn:(UITableView*) aView andTitle:(NSString*) aTitle  andArray:(NSArray*) aArray;
{
   [JMPickerView PopViewWithYYString:aString andIn:aView andTitle: aTitle  andArray:aArray with:nil];
}
+(void)PopViewWithYYString:(NSMutableString*)aString andIn:(UITableView*) aView andTitle:(NSString*) aTitle  andArray:(NSArray*) aArray with:(id<JMPickerViewDelegate>) aDelegate
{
    JMPickerView* instance  = [JMPickerView getInstance];
    
    if (isIOS8) {
        
        instance.sheetVC.iDelegate = aDelegate;
        instance.sheetVC.YYSelString = aString;
        instance.sheetVC.arrayPickView = aArray;
        instance.sheetVC.titleText = aTitle;
        instance.sheetVC.table = aView;
        instance.sheetVC.pickType = JMPickerNormal;
        
        AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        UIViewController* rootVC = delegate.window.rootViewController;
        
        
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
        instance.sheetVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
#endif
        UIViewController* presentingVC = delegate.window.rootViewController;
        if (presentingVC.presentedViewController) {
            presentingVC = presentingVC.presentedViewController;
        }

        [presentingVC presentViewController:instance.sheetVC animated:YES completion:^{
            //instance.sheetVC.titleLabel.text = aTitle;
        }];
        
    }else{
        instance._titleLabel.text = aTitle;
        instance._YYSelString = aString;
        instance._tableView = aView;
        instance.iDelegate = aDelegate;
        if (instance._arrayPickView != aArray)
        {
            [instance._pickView selectRow:instance._selectRow inComponent:0 animated:NO];
        }
        instance._arrayPickView = aArray;
        [instance._actionSheet showInView:instance._tableView];
        [instance._pickView reloadAllComponents];
    }
}


+(void)PopViewWithYYString:(NSMutableString*)aString andIn:(UITableView*) aView andTitle:(NSString*) aTitle andArray:(NSArray*) aArray andYYSeleRow:(int*) aYYSelet
{
    JMPickerView* instance  = [JMPickerView getInstance];
    
    instance._YYSelectRow = aYYSelet;
    
    [JMPickerView PopViewWithYYString:aString andIn:aView andTitle: aTitle  andArray:aArray];
}


#pragma mark----------确定
-(void)selectDateAffirm
{
    if (!_arrayPickView.count)
        return;
    _selectRow = [self._pickView selectedRowInComponent:0];
    NSString* selString = [_arrayPickView objectAtIndex:_selectRow];
    
    
    [_YYSelString setString:selString];
    
    
    
    
    [_actionSheet dismissWithClickedButtonIndex:0 animated:YES]; 
    
    _YYSelString = nil;
    
    if ([self._tableView isKindOfClass:[UITableView class]])
    {
        [_tableView reloadData];
    }
    //[_tableView reloadData];
    
    
    if (_YYSelectRow)
    {
        *_YYSelectRow  = _selectRow;
        _YYSelectRow  = nil;
    }
    
    if (self.iDelegate)
    {
        [self.iDelegate didSeleted:_selectRow];
        self.iDelegate = nil;
    }
    
    //点击完重置为0
    _selectRow = 0;
    //objc_msgSend(self,@selector(close:),date);

}

#pragma mark----------取消
-(void)selectDateCanceled
{
    
    _YYSelString = nil;
    [_actionSheet dismissWithClickedButtonIndex:0 animated:YES]; 
    //objc_msgSend(self,@selector(close:));
    
    if (_YYSelectRow)
    {
        _YYSelectRow  = nil;
    }
    
    //点击完重置为0
    _selectRow = 0;
}

//pickerView的内容是：当前月及往前推5个月（共6个月），表示形式为：2012年2月
+ (NSMutableArray*) getThePickViewDateArray{
	NSMutableArray *arrayDate = [[[NSMutableArray alloc] initWithCapacity:7] autorelease];
	
	NSString *strKong = @"               ";
	NSDate *nowDate = [NSDate date];
	NSString *strYear = [[nowDate description] substringToIndex:4];
	int intYear = [strYear intValue];
	NSString *strMonth = [[[nowDate description] substringFromIndex: 5] substringToIndex:2];
	int intMonth = [strMonth intValue];
	if (intMonth>=6) {
		int a = intMonth - 6;
		for (int i=intMonth; i>a; i--) {
			NSString *strDate = [NSString stringWithFormat:@"%@%d年%d月",strKong,intYear,i];
			[arrayDate addObject: strDate];
		}
	}else {
		int b = 6-intMonth;
		for (int j=intMonth; j>0; j--) {
			NSString *strDate = [NSString stringWithFormat:@"%@%d年%d月",strKong,intYear,j];
			[arrayDate addObject: strDate];
		}
		
		int lastYear = intYear - 1;
		for (int k=12; ; k--) {
			if (b==0) {
				break;
			}
			
			NSString *strDate = [NSString stringWithFormat:@"%@%d年%d月",strKong,lastYear,k];
			[arrayDate addObject: strDate];
			b--;
		}
	}
    
    return arrayDate ;

	
}

#pragma mark pickerView  methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
	return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if ([self._arrayPickView count]==0)
        pickerView.userInteractionEnabled=NO;
    else
        pickerView.userInteractionEnabled=YES;
	return [self._arrayPickView count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (self._arrayPickView.count>row)
        return [self._arrayPickView objectAtIndex: row];
    else
        return @"";
    
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	[pickerView reloadAllComponents];
    _selectRow = row;
	//self._strSeleted = [self._arrayPickView objectAtIndex: row];
}
#pragma mark -


- (void)dealloc {
	[_arrayPickView release];
	[_pickView release];
	[_titleLabel release];
	[_YYSelString release];
    [_actionSheet release];
    [_tableView release];
    [_sheetVC release];
    [super dealloc];
}

#pragma  mark - instance
+ (id)allocWithZone:(NSZone *)zone
{
    if (_Instance_JMPickerViews == nil) 
    {
        _Instance_JMPickerViews = [super allocWithZone:zone];
        return _Instance_JMPickerViews;  // assignment and return on first allocation
    }
    
    return nil;
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (unsigned)retainCount
{
    return UINT_MAX;  //denotes an object that cannot be released
}

- (oneway void)release
{
    
    //do nothing
}

- (id)autorelease
{
    return self;
}

//-----------------------
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(5, 0.0f, [pickerView rowSizeForComponent:component].width-10, [pickerView rowSizeForComponent:component].height)] autorelease];
    label.backgroundColor=[UIColor clearColor];
    label.font=[UIFont systemFontOfSize:18];
    label.adjustsFontSizeToFitWidth = YES;
    label.textAlignment = UITextAlignmentCenter;
    if (self._arrayPickView.count>row)
        label.text = [self._arrayPickView objectAtIndex: row];
    else
        label.text = @"";
    
    return label;
}

@end
